package com.javabasic.net.telnet;

import com.javabasic.testinterface.NotNullTest;
import org.apache.commons.net.telnet.TelnetClient;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.*;

/**
 * @Author xiongmin
 * @Description TODO 测试服务器的端口是否打开
 * @Date 2019/10/23 12:14
 * @Version 1.0
 *
 * Slf4J  https://www.cnblogs.com/a8457013/p/7909780.html
 **/
public class Telnet {
    static Logger logger = LoggerFactory.getLogger(NotNullTest.class);

    @Test
    public void stest() {
        long start1 = System.currentTimeMillis();
        checkTCP("120.90.90.90", 8789);
        long end1 = System.currentTimeMillis();
        System.out.println(end1 - start1);

        long start2 = System.currentTimeMillis();
        checkTCP("120.79.66.125", 8789);
        long end2 = System.currentTimeMillis();
        System.out.println(end2 - start2);

        long start3 = System.currentTimeMillis();
        checkTCP("192.168.1.145", 80);
        long end3 = System.currentTimeMillis();
        System.out.println(end2 - start2);
    }


    public static boolean checkTCP(String addr, int port) {
        logger.info("测试服务器：" + addr + ":" + port);

        TelnetClient telnet;
        telnet = new TelnetClient();
        try {
            telnet.setConnectTimeout(3000);
            telnet.connect(addr, port);
            logger.info("连接成功");
            return true;
        } catch (IOException e) {
            logger.error("检测服务器端口失败：" + e.getMessage());
        } finally {
            try {
                telnet.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static boolean checkUDP(String addr, int port) {
        boolean flag = true;
        DatagramSocket ds = null;
        try {
            DatagramPacket sendDp;
            DatagramPacket receiveDp;
            String serverHost = addr;
            int serverPort = port;
            ds = new DatagramSocket();
            byte[] buf = "hello,UDP协议！来自星星的问候……".getBytes();
            sendDp = new DatagramPacket(buf, buf.length, InetAddress.getByName(serverHost), serverPort);
            ds.send(sendDp);

            logger.info("消息发送成功");
            byte[] bufr = new byte[1024];
            receiveDp = new DatagramPacket(bufr, bufr.length);
            ds.setSoTimeout(3000); // 单位是毫秒
            ds.receive(receiveDp);
            byte[] response = receiveDp.getData();
            int len = receiveDp.getLength();
            String s = new String(response, 0, len);
            if (s.contains("recvfrom: connection refused")) {
                logger.info("服务器端口未开通");
                flag = false;
            } else {
                logger.info("服务器端口已经开通");
            }
            logger.info("服务器端反馈为： " + s);

        } catch (UnknownHostException e) {
            logger.error("检测服务器端口失败：" + e.getMessage());
            flag = false;
        } catch (SocketException e) {
            logger.error("检测服务器端口失败：" + e.getMessage());
            flag = false;
        } catch (SocketTimeoutException e) { // 超时异常视为，端口打开
        } catch (IOException e) {
            logger.error("检测服务器端口失败：" + e.getMessage());
            flag = false;
        } finally {
            ds.close();
        }
        return flag;

    }
}
